package com.iphaeton.lms.course.scorm12.runtime.client;

import com.iphaeton.lms.course.scorm12.DebugIndicator;
import com.iphaeton.lms.course.scorm12.datamodel.SCODataManager;
import java.io.ObjectInputStream;
import java.io.PrintStream;
import java.io.Serializable;
import java.net.URL;

public class ServletProxy
{
  private static boolean _Debug = DebugIndicator.ON;
  private URL servletURL;
  private String sessionid;

  public ServletProxy(URL url, String sessionid)
  {
    this.servletURL = url;
    this.sessionid = sessionid;
  }

  public SCODataManager GetSCOData()
  {
    SCODataManager empty;
    if (_Debug)
    {
      System.out.println("In ServletProxy::GetSCOData()");
    }

    try
    {
      String servletCommand = "cmigetcat";

      Serializable[] data = { servletCommand };

      if (_Debug)
      {
        System.out.println("Before postObjects()");
      }

      ObjectInputStream in = 
        ServletWriter.postObjects(this.servletURL, data, this.sessionid);

      if (_Debug)
      {
        System.out.println("Back In ServletProxy::GetSCOData()");
        System.out.println("Attempting to read servlet response now...");
      }

      SCODataManager scoData = (SCODataManager)in.readObject();

      if (_Debug)
      {
        System.out.println("Read servlet response successfully.");
        System.out.println("Closing input stream");
      }

      in.close();

      return scoData;
    }
    catch (Exception e)
    {
      if (_Debug)
      {
        System.out.println(
          "Exception caught In ServletProxy::GetSCODataData()");
        System.out.println(e.getMessage());
      }

      e.printStackTrace();
      empty = new SCODataManager(); }
    return empty;
  }

  public String PutSCOData(SCODataManager scoData)
  {
    try
    {
      if (_Debug)
      {
        System.out.println("In ServletProxy::PutSCOData()");
      }

      String servletCommand = "cmiputcat";

      Serializable[] data = { servletCommand, scoData };

      ObjectInputStream in = 
        ServletWriter.postObjects(this.servletURL, data, this.sessionid);

      in.close();
      String result = "OK";
      return result;
    }
    catch (Exception e)
    {
      if (_Debug)
      {
        System.out.println(
          "Exception caught In ServletProxy::PutSCOData()");
        System.out.println(e.getMessage());
      }

      e.printStackTrace(); }
    return "FAILED";
  }
}